<template>
	<conf-module-container ref="refConfModuleContainer" class="equipment-form-page-container">
		<template #Slot-Conf-Module-Header>
			<global-svg-icon
				icon-name="return"
				width="18px"
				height="18px"
				class="header-icon"
				style="margin-right: 8px; cursor: pointer"
				@click="router.go(-1)"
			></global-svg-icon>
			<p class="font-20-bold bread-crumb-title" style="color: #f0f6fc">
				{{ !route.query.id ? '添加设备' : '编辑设备' }}
			</p>
		</template>

		<template #Slot-Conf-Module-Content>
			<div style="display: flex; align-items: flex-start; justify-content: center; padding-bottom: 40px">
				<div class="the-equipment-config">
					<div class="font-16-bold the-common-title">
						<global-svg-icon icon-name="config-title-tri" width="3px" height="18px" style="margin-right: 16px"></global-svg-icon>
						<div>{{ !route.query.id ? '新增设备' : '编辑设备' }}</div>
					</div>
					<div class="the-equipment-form">
						<a-form ref="formRef" :model="formData" name="equipment-configuration" layout="vertical" :rules="addRules">
							<a-form-item name="name" label="设备名称" style="margin-top: -32px">
								<a-input v-model:value="formData.name" :maxlength="10" placeholder="请输入"></a-input>
							</a-form-item>
							<a-form-item name="areaId" label="场景位置">
								<div class="form-item-location">
									<a-tree-select
										v-model:value="formData.areaId"
										show-search
										style="width: 100%"
										:dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
										placeholder="请选择"
										:field-names="{
											key: 'id',
											value: 'id',
											title: 'name',
											children: 'children'
										}"
										allow-clear
										tree-default-expand-all
										:tree-data="deviceManagementList"
									>
										<template #title="node">
											<a-tooltip>
												<template #title>{{ node.name }}</template>
												<p class="font-14 tree-node-title" style="margin-top: 4px">
													{{ node.name }}
												</p>
											</a-tooltip>
										</template>
									</a-tree-select>
								</div>
							</a-form-item>
							<a-form-item name="boxSerial" label="所属盒子">
								<a-select
									v-model:value="formData.boxSerial"
									placeholder="请输入"
									:options="deviceBoxSerialList"
									@change="changeBoxSerial"
								></a-select>
							</a-form-item>

							<a-form-item name="factory" label="厂家">
								<a-input v-model:value="formData.factory" :maxlength="10" placeholder="请输入"></a-input>
							</a-form-item>
							<a-form-item name="deviceStreamingProtocol" label="协议">
								<a-select
									ref="select"
									v-model:value.trim="formData.deviceStreamingProtocol"
									:options="deviceStreamingProtocolOption"
									placeholder="请输入协议"
									@change="changeProtocol"
								></a-select>
							</a-form-item>
							<template v-if="formData.deviceStreamingProtocol == 0">
								<a-form-item name="address" label="链接地址">
									<a-input
										v-model:value.trim="formData.address"
										:maxlength="100"
										placeholder="请输入链接地址（rtsp://账号:密码@IP:端口）"
									></a-input>
								</a-form-item>
							</template>
							<a-form-item name="deviceType" label="设备类型">
								<a-select
									v-model:value="formData.deviceType"
									placeholder="请输入"
									:options="deviceTypeList"
									@change="changeType"
								></a-select>
							</a-form-item>
							<template v-if="formData.deviceStreamingProtocol == 1">
								<a-form-item name="sipUsername" label="SIP用户名">
									<a-input v-model:value.trim="formData.sipUsername" :maxlength="50" placeholder="请输入"></a-input>
								</a-form-item>
								<a-form-item name="sipPassword" label="SIP用户密码">
									<a-input v-model:value.trim="formData.sipPassword" :maxlength="50" placeholder="请输入"></a-input>
								</a-form-item>
							</template>

							<a-form-item style="margin-top: 32px">
								<template v-if="!editId">
									<a-button type="primary" html-type="submit" class="form-button" :loading="loading" @click="addDeviceSubmit"
										>添加</a-button
									>
									<a-button html-type="submit" class="form-button" @click="continueDeviceSubmit">添加并继续</a-button>
									<a-button @click="cancelModal">取消</a-button>
								</template>
								<template v-else>
									<a-button
										v-if="!OfflineStatus"
										type="primary"
										html-type="submit"
										class="form-button"
										:loading="loading"
										@click="addDeviceSubmit"
										>保存</a-button
									>
									<a-button @click="cancelModal">取消</a-button>
								</template>
							</a-form-item>
						</a-form>
					</div>
				</div>

				<div v-if="formData.deviceStreamingProtocol == 1" class="server-information" style="margin-top: 0">
					<div class="title">
						<span class="font-16-bold the-common-title">
							<global-svg-icon
								icon-name="config-title-tri"
								width="3px"
								height="18px"
								style="margin-right: 16px; vertical-align: middle"
							></global-svg-icon>
							<div>SIP服务器信息</div>
						</span>
					</div>
					<div class="server-info item">
						<div class="server-item">
							<div class="label">ID</div>
							<div class="value">{{ SIPServerInfo?.id }}</div>
						</div>
						<div class="server-item">
							<div class="label">域</div>
							<div class="value">{{ SIPServerInfo.domain }}</div>
						</div>
						<div class="server-item">
							<div class="label">地址</div>
							<div class="value">{{ SIPServerInfo.ip }}</div>
						</div>
						<div class="server-item">
							<div class="label">端口</div>
							<div class="value">{{ SIPServerInfo.sipId }}</div>
						</div>
					</div>
				</div>
			</div>
		</template>
	</conf-module-container>

	<!-- <a-button type="text" class="device-close-icon alone-icon-button" v-throttle="cancelModal">
				<i class="iconfont icon-close-line"></i>
			</a-button> -->
</template>

<script setup lang="ts" name="cameras-form">
import { SelectProps } from 'ant-design-vue';
import { VerifyForm } from '@/global-utils/check';
import { Rule } from 'ant-design-vue/es/form';

import { ConfModuleContainer } from '../../components/index';
import { CameraManagementAPI } from '../../api';
const route = useRoute();
const router = useRouter();
const editId = route.query.id as string;
const formRef = ref();
const loading = ref<boolean>(false);
const $message: any = inject('$message');
const isOnLine = ref(false);
const OfflineStatus = ref(true);

// RTSP正则
const rtspRegex = /rtsp:\/\/([^:@]+):([^:@]+)@([^:/]+)/g;
const addRules: Record<string, Rule[]> = {
	name: [{ required: true, message: '请输入设备名称', trigger: 'blur' }],
	boxSerial: [{ required: true, message: '请选择所属盒子', trigger: 'change' }],
	areaId: [{ required: true, message: '请选择场景位置', trigger: 'change' }],
	factory: [{ required: true, message: '请输入厂家', trigger: 'blur' }],
	deviceType: [{ required: true, message: '请选择设备类型', trigger: 'blur' }],
	deviceStreamingProtocol: [{ required: true, message: '请输入协议', trigger: 'blur' }],
	address: [
		{ required: true, message: '请输入链接地址', trigger: 'blur' },
		{
			pattern: rtspRegex,
			message: '请输入正确的RTSP链接地址',
			trigger: 'blur'
		}
	],
	sipUsername: [{ required: true, message: '请输入SIP用户名', trigger: 'blur' }],
	sipPassword: [{ required: true, message: '请输入SIP用户密码', trigger: 'blur' }]
};
// SIP服务器信息
const SIPServerInfo = ref({ id: '', domain: '', ip: '', sipId: '' });
const cancelModal = (): void => {
	router.go(-1);
};

// 场景位置下拉框
let deviceManagementList = ref();
const treeDataFilter = (treeData: any) => {
	treeData.forEach((item: any) => {
		if (item.children && item.children.length) {
			if (item.children[0].type === 0) {
				item.childrenCopy = item.children;
				item.children = null;
			} else {
				treeDataFilter(item.children);
			}
		}
	});
	return treeData;
};
const addTreeAttribute = (arr: any): void => {
	for (let len = 0; len < arr.length; len++) {
		if (arr[len].children) {
			arr[len].disabled = true;
			addTreeAttribute(arr[len].children);
		}
	}
};

const getEquipInfo = async (): Promise<void> => {
	try {
		const res: TsRes = await CameraManagementAPI.treeData();
		if (res.code === 0) {
			deviceManagementList.value = treeDataFilter(res.data);
			addTreeAttribute(deviceManagementList.value);
		}
	} catch (error) {
		// console.log('error111', error);
	}
};
// 所属盒子下拉框
const deviceBoxSerialList = ref<any>([]);
const OnLinedeviceBoxSerialList = ref<any>([]);
const Protocol = ref();
const getAllBoxSerialList = async (): Promise<void> => {
	deviceBoxSerialList.value = [];
	try {
		const res: TsRes = await CameraManagementAPI.boxSelectList();
		res.data.forEach((item: any) => {
			deviceBoxSerialList.value.push({ value: item.value, label: item.label });
			OnLinedeviceBoxSerialList.value.push(item.value);
		});
	} catch (error) {
		console.log('error111', error);
	}
};
const deviceTypeList = [
	{ value: 1, label: '普通摄像头' },
	{ value: 2, label: '红外测温摄像头' },
	{ value: 3, label: '枪球联动摄像头' }
];
// 获取盒子SIP信息
const BoxSerial = ref('');
const getBoxSipInfos = async (): Promise<void> => {
	const res: TsRes = await CameraManagementAPI.getBoxSipInfo({
		boxSerial: BoxSerial.value
	});
	SIPServerInfo.value = res.data;
};
// 选择所属盒子
const changeBoxSerial = (val: unknown): void => {
	BoxSerial.value = val as string;
	if (Protocol.value === 1 && BoxSerial.value?.length !== 0) {
		getBoxSipInfos();
	}
};

// 选择协议
const changeProtocol = (ProtocolVal: unknown): void => {
	Protocol.value = ProtocolVal as number | string;
	if (ProtocolVal === 1 && BoxSerial.value?.length !== 0 && isOnLine.value) {
		getBoxSipInfos();
	}
};
//选择设备类型
const changeType = (ProtocolVal: unknown): void => {
	formData.deviceType = ProtocolVal as number | string;
};
// 表单数据
const boxName = ref();
const formData = reactive<any>({ deviceStreamingProtocol: 0, deviceType: 1 });
const deviceStreamingProtocolOption = ref<SelectProps['options']>([
	{
		value: 0,
		label: 'RTSP'
	},
	{
		value: 1,
		label: 'GB/T 28181'
	}
]);
// 获取编辑的数据
const boxDeviceId = ref();
const getInfo = async (): Promise<any> => {
	if (!editId) {
		return false;
	}
	try {
		formData.id = editId;
		const res: TsRes = await CameraManagementAPI.detailCamera(editId);
		if (res.code === 0) {
			formData.name = res.data.name;
			formData.factory = res.data.factory;
			formData.deviceType = res.data.deviceType;
			formData.areaId = res.data.areaId;
			formData.boxSerial = res.data.boxName;
			formData.address = res.data.address;
			formData.sipUsername = res.data.sipUsername;
			formData.deviceStreamingProtocol = res.data.deviceStreamingProtocol;
			formData.sipPassword = res.data.sipPassword;
			BoxSerial.value = res.data.boxSerial;
			boxName.value = res.data.boxName;
			boxDeviceId.value = res.data.boxDeviceId;
			if (!OnLinedeviceBoxSerialList.value.indexOf(res.data.boxName)) {
				isOnLine.value = true;
			}
		}
	} catch (error) {
		//
	}
};

// 添加
const addDeviceSubmit = (): void => {
	console.log(boxDeviceId.value, 'boxDeviceId.value');

	VerifyForm(formRef, async () => {
		formData.boxSerial = BoxSerial.value;
		formData.boxName = boxName.value;
		formData.boxDeviceId = boxDeviceId.value;
		const newForm = JSON.parse(JSON.stringify(formData));
		loading.value = true;
		try {
			// 接口
			let res: TsRes = !editId ? await CameraManagementAPI.addCamera(newForm) : await CameraManagementAPI.editCamera(newForm);
			if (res.code === 0) {
				$message.success('保存成功');

				router.go(-1);
			}
		} finally {
			loading.value = false;
		}
	});
};
// 继续添加
const continueDeviceSubmit = async (): Promise<void> => {
	VerifyForm(formRef, async () => {
		const newForm = JSON.parse(JSON.stringify(formData));
		// loading.value = true;
		console.log(newForm);

		// 接口
		const res: TsRes = await CameraManagementAPI.addCamera(newForm);
		console.log(res);

		if (res.code === 0) {
			$message.success('保存成功');
			console.log(res);
			formData.name = '';
			formData.boxSerial = undefined;
			formData.areaId = undefined;
			formData.factory = '';
			formData.deviceType = 1;
			formData.deviceStreamingProtocol = 0;
			formData.sipUsername = '';
			formData.sipUsesipPasswordrname = '';
			formData.address = '';
		}
	});
};

const watchEffectStop = watchEffect(() => {
	if (formData.name) {
		formData.name = formData.name.replace(/\s+/, '');
	}
	if (formData.factory) {
		formData.factory = formData.factory.replace(/\s+/, '');
	}
	if (formData.address) {
		formData.address = formData.address.replace(/\s+/, '');
	}
	if (formData.sipUsername) {
		formData.sipUsername = formData.sipUsername.replace(/\s+/, '');
	}
	if (formData.sipPassword) {
		formData.sipPassword = formData.sipPassword.replace(/\s+/, '');
	}
});

onMounted(async () => {
	await getAllBoxSerialList();
	await getEquipInfo();
	await getInfo();
	// console.log(formData.boxSerial, 'formData.boxSerial');
	OfflineStatus.value = route.query.status === '0' ? true : false;

	if (formData.boxSerial && formData.deviceStreamingProtocol === 1) {
		getBoxSipInfos();
	}
});
onUnmounted(() => {
	watchEffectStop();
});
</script>

<style lang="less">
.equipment-form-page-container {
	.title {
		display: flex;
		font-size: 20px;
		font-weight: 700;
		font-style: normal;
		line-height: 28px; /* 140% */
		align-items: center;
		color: @text01;
	}

	.ant-form {
		.ant-form-item {
			.ant-form-item-label {
				margin-top: 32px;
			}
		}
	}

	.the-common-title {
		display: flex;
		margin-bottom: 16px;
		color: @text01;
		align-items: center;
	}

	.the-equipment-config {
		.the-equipment-form {
			width: 360px;
			border: 1px solid @borderColor02;
			border-radius: 4px;
			padding: 20px 20px 40px;
			background: @background02;
			box-shadow: 0 40px 180px 0 rgba(0, 0, 0, 0.35);

			.form-button {
				margin-right: 8px;
			}
		}
	}

	.server-information {
		width: 360px;
		height: 368px;
		margin: 40px 0 0 80px;

		.title {
			display: flex;
		}

		.server-info {
			height: 328px;
			border: 1px solid @borderColor02;
			border-radius: 4px;
			padding: 12px 20px;
			background: #101b2f;
			box-shadow: 0 40px 180px 0 rgba(0, 0, 0, 0.35);

			.server-item {
				border-bottom: 1px solid @borderColor02;
				padding: 12px 0;
				line-height: 22px;

				.label {
					margin-bottom: 8px;
					line-height: 22px;
					color: @text03;
				}

				.value {
					color: @text01;
				}
			}

			.server-item:last-child {
				border-bottom: none;
			}
		}
	}

	.tree-node-title {
		background: transparent !important;

		&:active {
			background: transparent !important;
		}
	}
}

:where(.css-dev-only-do-not-override-kqecok).ant-tree .ant-tree-node-content-wrapper.ant-tree-node-selected,
:where(.css-dev-only-do-not-override-kqecok).ant-tree .ant-tree-checkbox + span.ant-tree-node-selected {
	background-color: @background01 !important;
}
</style>
